package com.hyacinth.cloudnote.modules.note.service;

import com.hyacinth.cloudnote.common.exception.ExceptionHolder;
import com.hyacinth.cloudnote.common.security.CurrentUserContextHolder;
import com.hyacinth.cloudnote.common.security.UserPrincipal;
import com.hyacinth.cloudnote.modules.note.model.Favorite;
import com.hyacinth.cloudnote.modules.note.model.Note;
import com.hyacinth.cloudnote.modules.note.model.NoteBook;
import com.hyacinth.cloudnote.modules.note.model.Tag;
import com.hyacinth.cloudnote.modules.note.repository.FavoriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000000001;
import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000005001;

/**
 * Favorite实体对应的业务逻辑Service实现类
 * @author zhangfb
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FavoriteService {

    @Autowired
    private FavoriteRepository favoriteRepository;

    public Favorite save(Favorite model) {
        // 获取当前登陆用户
        UserPrincipal currentUser = CurrentUserContextHolder.getCurrentUser();
        Optional<Favorite> optional = favoriteRepository.findByNoteAndCreatedBy(model.getNote(), currentUser.getId());
        if (optional.isPresent()) {
            throw ExceptionHolder.serviceException(E1000005001, currentUser.getMobile(), "笔记-" + model.getNote().getTitle());
        }
        optional = favoriteRepository.findByNoteBookAndCreatedBy(model.getNoteBook(), currentUser.getId());
        if (optional.isPresent()) {
            throw ExceptionHolder.serviceException(E1000005001, currentUser.getMobile(), "笔记本-" + model.getNoteBook().getName());
        }
        optional = favoriteRepository.findByTagAndCreatedBy(model.getTag(), currentUser.getId());
        if (optional.isPresent()) {
            throw ExceptionHolder.serviceException(E1000005001, currentUser.getMobile(), "标签-" + model.getTag().getName());
        }
        return favoriteRepository.save(model);
    }

    public void delete(UUID id) {
        Favorite favorite = favoriteRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(E1000000001, "收藏夹-" + id));
        favoriteRepository.delete(favorite);
    }

    public void deleteByNoteBook(NoteBook noteBook, List<Note> notes) {
        if (!CollectionUtils.isEmpty(notes)) {
            favoriteRepository.deleteAllByNoteIn(notes);
        }
        favoriteRepository.deleteAllByNoteBook(noteBook);
    }

    public void deleteByNote(Note note) {
        favoriteRepository.deleteAllByNote(note);
    }

    public void deleteByTag(Tag tag) {
        favoriteRepository.deleteAllByTag(tag);
    }

}
